import os
import math
import psycopg2
from QRoute import QRoute
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import QDateTime, QTimer
from PyQt5.QtWidgets import QApplication, QWidget, QDialog, QMessageBox, QMainWindow, QStatusBar, QLabel, QAction
from ui import OrderDialog
from pytdx.hq import TdxHq_API

class CustomError(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)

class Widget(QWidget):
    def __init__(self, parent=None):
        super(QWidget, self).__init__(parent)
        self.ui_orderDialog = OrderDialog.Ui_NewOrderDialog()
        self.ui_orderDialog.setupUi(self)
        self.ui_orderDialog.retranslateUi(self)
        self.form = dict()
        self.textBrowser = dict()

    def setupDefault(self):
        _translate = QtCore.QCoreApplication.translate
        self.ui_orderDialog.LineEditStockCode.setText('')
        self.ui_orderDialog.LineEditStockLabel.setText('')
        self.ui_orderDialog.ComboBoxOperate.setCurrentIndex(0)
        self.ui_orderDialog.DoubleSpinBoxPrice.setValue(0.00)
        self.ui_orderDialog.SpinBoxNumber.setValue(0)
        self.ui_orderDialog.DoubleSpinBoxLosses.setValue(0.00)
        self.ui_orderDialog.DateTimeEdit.setDateTime(QDateTime.currentDateTime())
        self.textBrowser.clear()
        self.ui_orderDialog.ComboBoxAccount.clear()
        self.ui_orderDialog.ComboBoxAccount.addItem(_translate("NewOrderDialog", '请选择证券账户'))
        self.ui_orderDialog.ComboBoxOperate.clear()
        self.ui_orderDialog.ComboBoxOperate.addItem(_translate("NewOrderDialog", '请选择交易方向'))
        self.ui_orderDialog.ComboBoxAllocation.clear()
        self.ui_orderDialog.ComboBoxAllocation.addItem(_translate("NewOrderDialog", '请选择交易模式'))
        for row in self.account:
            if (row['account_type'] == str('account.stock')):
                self.ui_orderDialog.ComboBoxAccount.addItem(_translate("NewOrderDialog", row['account_label']))
                if (row['is_default'] is True):
                    self.ui_orderDialog.ComboBoxAccount.setCurrentText(row['account_label'])
        for row in self.dictionary:
            if (row['kind'] == str('stock.trade.type')):
                self.ui_orderDialog.ComboBoxOperate.addItem(_translate("NewOrderDialog", row['label']))
            if (row['kind'] == str('asset.allocation')):
                self.ui_orderDialog.ComboBoxAllocation.addItem(_translate("NewOrderDialog", row['label']))

    def accept(self):
        try:
            conn = self.unit.dbConnect(self.setting.pgsql)
            cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
            if (self.ui_orderDialog.ComboBoxAccount.currentIndex() == 0):
                raise CustomError('证券账户未做选择！')
            for row in self.account:
                if(row['account_type'] == 'account.stock' and row['account_label'] == self.ui_orderDialog.ComboBoxAccount.currentText()):
                    account_id = row['uuid']
            if(self.ui_orderDialog.ComboBoxOperate.currentIndex() == 0):
                raise CustomError('交易方向未做选择！')
            else:
                if (self.ui_orderDialog.LineEditStockCode.text() == '' and self.ui_orderDialog.ComboBoxOperate.currentIndex() not in [8, 9, 10, 11]):
                    raise CustomError('证券代码不能为空！')
                if (self.ui_orderDialog.LineEditStockLabel.text() == '' and self.ui_orderDialog.ComboBoxOperate.currentIndex() not in [8, 9, 10, 11]):
                    raise CustomError('证券代码不合法！')
                if (self.ui_orderDialog.DoubleSpinBoxPrice.value() == 0 and self.ui_orderDialog.ComboBoxOperate.currentIndex() in [1, 2, 3, 4, 5, 6]):
                    raise CustomError('证券交易单价不能为零！')
                if (self.ui_orderDialog.SpinBoxNumber.value() == 0 and self.ui_orderDialog.ComboBoxOperate.currentIndex() in [1, 2, 3, 4, 5, 7]):
                    raise CustomError('证券交易数量不能为零！')
            if(self.ui_orderDialog.ComboBoxOperate.currentIndex() in [1, 2]):
                if(self.ui_orderDialog.ComboBoxAllocation.currentIndex() == 0):
                    raise CustomError('交易模式未做选择！')
                else:
                    if (self.ui_orderDialog.ComboBoxAllocation.currentText() == str('价格行为')):
                        if (self.ui_orderDialog.DoubleSpinBoxLosses.value() == 0):
                            raise CustomError('证券交易止损价不能为零！')
                        if(self.ui_orderDialog.ComboBoxReasons.currentIndex() == 0):
                            raise CustomError('证券交易理由不能为空！')
                        cursor.execute("INSERT INTO trading.transaction(account_id, stock_code, operate, allocation, price, number, stop_losses, reasons, datetime) VALUES ('%s', '%s', '%s', '%s', %s, %s, %s, '%s', '%s') RETURNING abstracts" % (
                                       account_id,
                                       self.ui_orderDialog.LineEditStockCode.text(),
                                       self._getDictionaryInfo('stock.trade.type', self.ui_orderDialog.ComboBoxOperate.currentText())['code'],
                                       self._getDictionaryInfo('asset.allocation', self.ui_orderDialog.ComboBoxAllocation.currentText())['code'],
                                       self.ui_orderDialog.DoubleSpinBoxPrice.value(),
                                       self.ui_orderDialog.SpinBoxNumber.value(),
                                       self.ui_orderDialog.DoubleSpinBoxLosses.value(),
                                       self._getDictionaryInfo(trade + '.price.action', self.ui_orderDialog.ComboBoxReasons.currentText())['code'],
                                       self.ui_orderDialog.DateTimeEdit.dateTime().toString("yyyy-MM-dd HH:mm:ss")))
                    else:
                        cursor.execute("INSERT INTO trading.transaction(account_id, stock_code, operate, allocation, price, number, datetime) VALUES ('%s', '%s', '%s', '%s', %s, %s, '%s') RETURNING abstracts" % (
                                       account_id,
                                       self.ui_orderDialog.LineEditStockCode.text(),
                                       self._getDictionaryInfo('stock.trade.type', self.ui_orderDialog.ComboBoxOperate.currentText())['code'],
                                       self._getDictionaryInfo('asset.allocation', self.ui_orderDialog.ComboBoxAllocation.currentText())['code'],
                                       self.ui_orderDialog.DoubleSpinBoxPrice.value(),
                                       self.ui_orderDialog.SpinBoxNumber.value(),
                                       self.ui_orderDialog.DateTimeEdit.dateTime().toString("yyyy-MM-dd HH:mm:ss")))
            elif (self.ui_orderDialog.ComboBoxOperate.currentIndex() in [3, 4, 5]):
                # 申购证券、转入持仓、转出持仓
                cursor.execute("INSERT INTO trading.transaction(account_id, stock_code, operate, allocation, price, number, datetime) VALUES ('%s', '%s', '%s', '%s', %s, %s, '%s') RETURNING abstracts" % (
                               account_id,
                               self.ui_orderDialog.LineEditStockCode.text(),
                               self._getDictionaryInfo('stock.trade.type', self.ui_orderDialog.ComboBoxOperate.currentText())['code'],
                               'regular_way',
                               self.ui_orderDialog.DoubleSpinBoxPrice.value(),
                               self.ui_orderDialog.SpinBoxNumber.value(),
                               self.ui_orderDialog.DateTimeEdit.dateTime().toString("yyyy-MM-dd HH:mm:ss")))
            elif (self.ui_orderDialog.ComboBoxOperate.currentIndex() == 6):
                # 证券股息
                cursor.execute("INSERT INTO trading.transaction(account_id, stock_code, operate, amount, datetime) VALUES ('%s', '%s', '%s', %s, '%s') RETURNING abstracts" % (
                               account_id,
                               self.ui_orderDialog.LineEditStockCode.text(),
                               'stockDividend',
                               self.ui_orderDialog.DoubleSpinBoxPrice.value(),
                               self.ui_orderDialog.DateTimeEdit.dateTime().toString("yyyy-MM-dd HH:mm:ss")))
            elif(self.ui_orderDialog.ComboBoxOperate.currentIndex() == 7):
                # 证券派股
                cursor.execute("INSERT INTO trading.transaction(account_id, stock_code, operate, number, datetime) VALUES ('%s', '%s', '%s', %s, '%s') RETURNING abstracts" % (
                               account_id,
                               self.ui_orderDialog.LineEditStockCode.text(),
                               'shareAllotment',
                               self.ui_orderDialog.SpinBoxNumber.value(),
                               self.ui_orderDialog.DateTimeEdit.dateTime().toString("yyyy-MM-dd HH:mm:ss")))
            elif (self.ui_orderDialog.ComboBoxOperate.currentIndex() in [8, 9, 10, 11]):
                # 国债收益、账户利息、银转证、证转银
                cursor.execute("INSERT INTO trading.transaction(account_id, operate, amount, datetime) VALUES ('%s', '%s', %s, '%s') RETURNING abstracts" % (
                               account_id,
                               self._getDictionaryInfo('stock.trade.type', self.ui_orderDialog.ComboBoxOperate.currentText())['code'],
                               self.ui_orderDialog.DoubleSpinBoxPrice.value(),
                               self.ui_orderDialog.DateTimeEdit.dateTime().toString("yyyy-MM-dd HH:mm:ss")))
            else:
                raise CustomError('证券交易方向出现错误，超出界限！')
            QMessageBox.about(self, "新建订单操作成功", str(cursor.fetchone()['abstracts']))
        except CustomError as e:
            QMessageBox.warning(self, "表单填写失误", str(e.value))
        except Exception as e:
            print(str(e))
            QMessageBox.warning(self, "数据库操作失败", str(e))
        else:
            self.close()
        finally:
            self.unit.dbDisconnect(conn)

    def reject(self):
        reply = QMessageBox.question(self, "是否确认？", "你真的要取消创建新的订单吗？", QMessageBox.Yes | QMessageBox.Cancel)
        if (reply == QMessageBox.Yes):
            self.close()

    def changedAccound(self):
        if (self.ui_orderDialog.ComboBoxAccount.currentIndex() != 0):
            for row in self.account:
                if (row['account_type'] == 'account.stock' and row['account_label'] == self.ui_orderDialog.ComboBoxAccount.currentText()):
                    self.form['account_id'] = row['uuid']
                    self.form['balance'] = row['balance']
                    self.textBrowser['account'] = '证券账户：' + row['account_label'] + '，资金余额：￥' + str(row['balance'])
        else:
            self.textBrowser['account'] = '证券账户：尚未选择证券账户，请选择证券账户！'
        self._textBrowserMarkdown()

    def changedStockCode(self):
        try:
            conn = self.unit.dbConnect(self.setting.pgsql)
            cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
            cursor.execute("SELECT stock_code, stock_label, stock_market, stock_type FROM trading.stock WHERE stock_code = '%s';" % self.ui_orderDialog.LineEditStockCode.text())
            result = cursor.fetchone()
            self.textBrowser['stock'] = '交易证券：(' + result['stock_code'] + ') ' + result['stock_label'] + ' | ' + result['stock_type'] + ' | ' + result['stock_market']
            self._textBrowserMarkdown()
            api = TdxHq_API()  # 创建对象
            with api.connect('119.147.212.81', 7709):
                if (result['stock_market'] == '深圳证券交易所'):
                    market = 0
                elif (result['stock_market'] == '上海证券交易所'):
                    market = 1
                elif (result['stock_market'] == '北京证券交易所'):
                    market = 2
                data = api.get_security_quotes([(market, result['stock_code'])])
                self.ui_orderDialog.LineEditStockLabel.setText('(' + result['stock_code'] + ') ' + result['stock_label'] + ' | ' + result['stock_type'] + ' | ' + result['stock_market'])
                self.ui_orderDialog.DoubleSpinBoxPrice.setValue(data[0]['price'])
        except Exception as e:
            QMessageBox.warning(self, "操作失败", str(e))
        finally:
            self.unit.dbDisconnect(conn)

    def changedAllocation(self):
        self.ui_orderDialog.ComboBoxReasons.clear()
        if(self.ui_orderDialog.ComboBoxAllocation.currentText() == str('价格行为')):
            _translate = QtCore.QCoreApplication.translate
            self.ui_orderDialog.LabelLosses.setEnabled(True)
            self.ui_orderDialog.DoubleSpinBoxLosses.setEnabled(True)
            self.ui_orderDialog.LabelReasons.setEnabled(True)
            self.ui_orderDialog.ComboBoxReasons.setEnabled(True)
            if(self.ui_orderDialog.ComboBoxOperate.currentText() == '买入证券'):
                self.ui_orderDialog.ComboBoxReasons.addItem(_translate("NewOrderDialog", '请选择做多交易理由'))
                for row in self.dictionary:
                    if (row['kind'] == 'buy.price.action'):
                        self.ui_orderDialog.ComboBoxReasons.addItem(_translate("NewOrderDialog", row['label']))
            elif(self.ui_orderDialog.ComboBoxOperate.currentText() == '卖出证券'):
                self.ui_orderDialog.ComboBoxReasons.addItem(_translate("NewOrderDialog", '请选择做空交易理由'))
                for row in self.dictionary:
                    if (row['kind'] == 'sell.price.action'):
                        self.ui_orderDialog.ComboBoxReasons.addItem(_translate("NewOrderDialog", row['label']))
            else:
                self.ui_orderDialog.LabelLosses.setDisabled(True)
                self.ui_orderDialog.DoubleSpinBoxLosses.setDisabled(True)
                self.ui_orderDialog.LabelReasons.setDisabled(True)
                self.ui_orderDialog.ComboBoxReasons.setDisabled(True)
        else:
            self.ui_orderDialog.LabelLosses.setDisabled(True)
            self.ui_orderDialog.DoubleSpinBoxLosses.setDisabled(True)
            self.ui_orderDialog.LabelReasons.setDisabled(True)
            self.ui_orderDialog.ComboBoxReasons.setDisabled(True)

    def changedOperate(self):
        _translate = QtCore.QCoreApplication.translate
        self.textBrowser.clear()
        self._textBrowserMarkdown()
        if (self.ui_orderDialog.ComboBoxOperate.currentIndex() in [1, 2, 3, 4, 5]):
            # 申购证券, 转入持仓, 转出持仓
            self.ui_orderDialog.LabelStockCode.setEnabled(True)
            self.ui_orderDialog.LineEditStockCode.setEnabled(True)
            self.ui_orderDialog.LabelPrice.setEnabled(True)
            self.ui_orderDialog.DoubleSpinBoxPrice.setEnabled(True)
            self.ui_orderDialog.LabelNumber.setEnabled(True)
            self.ui_orderDialog.SpinBoxNumber.setEnabled(True)
            self.ui_orderDialog.LabelLosses.setDisabled(True)
            self.ui_orderDialog.DoubleSpinBoxLosses.setDisabled(True)
            self.ui_orderDialog.LabelAllocation.setEnabled(True)
            self.ui_orderDialog.ComboBoxAllocation.setEnabled(True)
            self.ui_orderDialog.LabelReasons.setDisabled(True)
            self.ui_orderDialog.ComboBoxReasons.setDisabled(True)
            self.ui_orderDialog.LabelPrice.setText(_translate("NewOrderDialog", "交易单价："))
            self.ui_orderDialog.LabelNumber.setText(_translate("NewOrderDialog", "交易数量："))
        elif (self.ui_orderDialog.ComboBoxOperate.currentIndex() == 7):
            # 证券派股
            self.ui_orderDialog.LabelStockCode.setEnabled(True)
            self.ui_orderDialog.LineEditStockCode.setEnabled(True)
            self.ui_orderDialog.LabelPrice.setDisabled(True)
            self.ui_orderDialog.DoubleSpinBoxPrice.setDisabled(True)
            self.ui_orderDialog.LabelNumber.setEnabled(True)
            self.ui_orderDialog.SpinBoxNumber.setEnabled(True)
            self.ui_orderDialog.LabelLosses.setDisabled(True)
            self.ui_orderDialog.DoubleSpinBoxLosses.setDisabled(True)
            self.ui_orderDialog.LabelAllocation.setDisabled(True)
            self.ui_orderDialog.ComboBoxAllocation.setDisabled(True)
            self.ui_orderDialog.LabelReasons.setDisabled(True)
            self.ui_orderDialog.ComboBoxReasons.setDisabled(True)
            self.ui_orderDialog.LabelNumber.setText(_translate("NewOrderDialog", "派股数量："))
        elif (self.ui_orderDialog.ComboBoxOperate.currentIndex() == 6):
            # 证券股息
            self.ui_orderDialog.LabelStockCode.setEnabled(True)
            self.ui_orderDialog.LineEditStockCode.setEnabled(True)
            self.ui_orderDialog.LabelPrice.setEnabled(True)
            self.ui_orderDialog.DoubleSpinBoxPrice.setEnabled(True)
            self.ui_orderDialog.LabelNumber.setDisabled(True)
            self.ui_orderDialog.SpinBoxNumber.setDisabled(True)
            self.ui_orderDialog.LabelLosses.setDisabled(True)
            self.ui_orderDialog.DoubleSpinBoxLosses.setDisabled(True)
            self.ui_orderDialog.LabelAllocation.setDisabled(True)
            self.ui_orderDialog.ComboBoxAllocation.setDisabled(True)
            self.ui_orderDialog.LabelReasons.setDisabled(True)
            self.ui_orderDialog.ComboBoxReasons.setDisabled(True)
            self.ui_orderDialog.LabelPrice.setText(_translate("NewOrderDialog", "股息金额："))
        elif (self.ui_orderDialog.ComboBoxOperate.currentIndex() in [8, 9, 10, 11]):
            # 国债收益, 账户利息, 银转证, 证转银
            self.ui_orderDialog.LabelStockCode.setDisabled(True)
            self.ui_orderDialog.LineEditStockCode.setDisabled(True)
            self.ui_orderDialog.LabelPrice.setEnabled(True)
            self.ui_orderDialog.DoubleSpinBoxPrice.setEnabled(True)
            self.ui_orderDialog.LabelNumber.setDisabled(True)
            self.ui_orderDialog.SpinBoxNumber.setDisabled(True)
            self.ui_orderDialog.LabelLosses.setDisabled(True)
            self.ui_orderDialog.DoubleSpinBoxLosses.setDisabled(True)
            self.ui_orderDialog.LabelAllocation.setDisabled(True)
            self.ui_orderDialog.ComboBoxAllocation.setDisabled(True)
            self.ui_orderDialog.LabelReasons.setDisabled(True)
            self.ui_orderDialog.ComboBoxReasons.setDisabled(True)
            self.ui_orderDialog.LabelPrice.setText(_translate("NewOrderDialog", "发生金额："))
        else:
           pass

    def changedPrice(self):
        if (self.ui_orderDialog.ComboBoxOperate.currentText() in ['买入证券', '卖出证券', '转出持仓', '证券股息']):
            try:
                conn = self.unit.dbConnect(self.setting.pgsql)
                cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
                cursor.execute("SELECT capitalized, number FROM trading.position WHERE stock_code = '%s' AND account_id = '%s'" % (self.ui_orderDialog.LineEditStockCode.text(), self.form['account_id']))
                result = cursor.fetchone()
                price = float(self.ui_orderDialog.DoubleSpinBoxPrice.value())
                if (self.ui_orderDialog.ComboBoxOperate.currentText() == '买入证券'):
                    full = math.floor(float(self.form['balance']) / price / 100) * 100
                    half = math.floor(float(self.form['balance']) / price / 100 / 2) * 100
                    third = math.floor(float(self.form['balance']) / price / 100 / 3) * 100
                    fourth = math.floor(float(self.form['balance']) / price / 100 / 4) * 100
                    fifth = math.floor(float(self.form['balance']) / price / 100 / 5) * 100
                    self.textBrowser['price'] = '买入单价：￥' + str(price) + '，根据账户现金余额，全仓：' + str(full) + '股，半仓：' + str(half) + '股，1/3仓：' + str(third) + '股，1/4仓：' + str(fourth) + '股，1/5仓：' + str(fifth) + '股'
                    if(result is not None):
                        self.textBrowser['price'] += '，持仓成本：￥' + result['capitalized'] + '持仓数量：' + result['number'] + '股'
                elif (self.ui_orderDialog.ComboBoxOperate.currentText() == '卖出证券'):
                    if (result is None):
                        QMessageBox.warning(self, "交易失败", '所卖出的股票，持仓量为零！')
                    else:
                        self.textBrowser['price'] = '卖出单价：￥' + str(price) + '，持仓成本：￥' + str(result['capitalized']) + '持仓数量：' + str(result['number']) + '股'
                else:
                    if (result is None):
                        QMessageBox.warning(self, "交易失败", '【' + self.ui_orderDialog.ComboBoxOperate.currentText() + '】交易操作时，持仓量不能为零！')
                    else:
                        if (self.ui_orderDialog.ComboBoxOperate.currentText() == '转出持仓'):
                            self.textBrowser['price'] = '转出单价：￥' + str(price) + '，持仓成本：￥' + result['capitalized'] + '持仓数量：' + result['number'] + '股'
                        else:
                            capitalized = str(round((float(result['capitalized']) * int(result['number']) + price) / int(result['number']), 2))
                            self.textBrowser['price'] = '派发证券股息，股息金额：￥' + str(price) + '，原持仓成本：￥' + str(result['capitalized']) + '调整后持仓成本：￥' + capitalized
            except Exception as e:
                print(e)
                QMessageBox.warning(self, "操作失败", str(e))
            else:
                self._textBrowserMarkdown()
            finally:
                self.unit.dbDisconnect(conn)

    def changedNumber(self):
        if (self.ui_orderDialog.ComboBoxOperate.currentText() in ['买入证券', '卖出证券', '转入持仓', '证券派股']):
            try:
                conn = self.unit.dbConnect(self.setting.pgsql)
                cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
                cursor.execute("SELECT capitalized, number FROM trading.position WHERE stock_code = '%s' AND account_id = '%s'" % (self.ui_orderDialog.LineEditStockCode.text(), self.form['account_id']))
                result = cursor.fetchone()
                number = int(self.ui_orderDialog.SpinBoxNumber.value())
                price = float(self.ui_orderDialog.DoubleSpinBoxPrice.value())
                amount = float(price * number)
                if (self.ui_orderDialog.ComboBoxOperate.currentText() == '买入证券' and price != 0):
                    if(amount > self.form['balance']):
                        QMessageBox.warning(self, "交易失败", '【买入证券】交易操作时，交易金额不能大于账户现金余额！')
                    else:
                        self.textBrowser['number'] = '买入数量：' + str(number) + '股，交易金额：￥' + str(round(amount, 2)) + '，占现金余额的' + str(round((amount/float(self.form['balance'])*100), 2)) + '%'
                        if (result is not None):
                            capitalized = str(round((float(result['capitalized']) * int(result['number']) + amount)/(int(result['number']) + number), 2))
                            self.textBrowser['number'] += '，买入后总持仓数量：' + str(number + result['number']) + '股，买入后持仓成本：￥' + capitalized
                elif (self.ui_orderDialog.ComboBoxOperate.currentText() == '卖出证券'):
                    if (result is None):
                        QMessageBox.warning(self, "交易失败", '【卖出证券】交易操作时，持仓量不能为零！')
                    else:
                        if (number > result['number']):
                            QMessageBox.warning(self, "交易失败", '【卖出证券】交易操作时，卖出数量不能大于持仓量！')
                        else:
                            self.textBrowser['number'] = '卖出数量；' + str(number) + '股，剩余持仓数量：' + str(result['number'] - number) + '股'
                elif (self.ui_orderDialog.ComboBoxOperate.currentText() == '转入持仓'):
                    self.textBrowser['number'] = '转入数量：' + str(number) + '股'
                    if (result is not None):
                        capitalized = str(round((float(result['capitalized']) * int(result['number']) + amount)/(int(result['number']) + number), 2))
                        self.textBrowser['number'] += '，转入后总持仓数量：' + str(number + result['number']) + '股，转入后持仓成本：￥' + capitalized
                else:
                    if (result is None):
                        QMessageBox.warning(self, "交易失败", '【证券派股】交易操作时，持仓量不能为零！')
                    else:
                        capitalized = str(round(float(result['capitalized']) * int(result['number'])/(int(result['number']) + number), 2))
                        self.textBrowser['number'] = '证券派股数量；' + str(number) + '股，派股后持仓数量：' + str(result['number'] - number) + '股，派股后持仓成本：￥' + capitalized
            except Exception as e:
                QMessageBox.warning(self, "操作失败", str(e))
            else:
                self._textBrowserMarkdown()
            finally:
                self.unit.dbDisconnect(conn)

    def _getDictionaryInfo(self, kind, label):
        for row in self.dictionary:
            if (row['kind'] == kind and row['label'] == label):
                return row

    def _textBrowserMarkdown(self):
        markdown = ''
        for val in self.textBrowser:
            markdown += '- ' + self.textBrowser[val] + ' \n'
        self.ui_orderDialog.textBrowser.setMarkdown(markdown)